package com.zzyl.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;

import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import io.github.classgraph.ResourceList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper  roleResourceMapper;
    @Override
    public PageResponse<RoleVo> findPostPage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<RoleVo> page = (Page<RoleVo>)roleMapper.findList(roleDto);
        PageResponse<RoleVo> of = PageResponse.of(page, RoleVo.class);
        return  of;
    }

    @Override
    public void addRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.findCheckedResources(roleId);
    }

    @Override
    public Boolean updateRole(RoleDto roleDto) {
//        转换后
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        //判断是否删除角色的资源
        if (ObjectUtil.isEmpty(roleDto.getCheckedDeptNos())){
            return true;
        }
        //删除角色资源下的中间信息
        roleResourceMapper.deleteRoleResourceById(role.getId());
        //保存角色资源中间信息
        String[] checkedResourceNos=roleDto.getCheckedResourceNos();
        List<RoleResource> roleResourceList = new ArrayList<>();
        for (String resourceNo : checkedResourceNos) {
            RoleResource roleResource = new RoleResource(role.getId(), resourceNo, "0");
            roleResourceList.add(roleResource);
        }
        if (CollUtil.isNotEmpty(roleResourceList)){
            roleResourceMapper.batchInsert(roleResourceList);
        }

        return true;
    }

    @Override
    public List<RoleVo> findAll() {
      List<RoleVo> roles= roleMapper.findList(new RoleDto());
      return  BeanUtil.copyToList(roles,RoleVo.class);
    }
}
